<?php

require_once("helper/UrlConversionHelper.php");
require_once("helper/StringFormattingHelper.php");

error_reporting(0);

class UrlParser {

	private $queue = array();
	private $pages = array();
	private $form_actions = array();
	private $current_url;
	private $root_url;

	const HIGH_RISK = "1-high";
	const MEDIUM_RISK = "2-medium";
	const LOW_RISK = "3-low";

	public function __construct($url)
	{
		$this->root_url = $url;
		$this->queue[] = $url;
	}

	public function parse()
	{
		$this->doparse();
		return $this->pages;
	}

	private function doparse()
	{
		while(count($this->queue) > 0)
		{
			$this->current_url = array_shift($this->queue);

      		echo "parsing |".$this->current_url."|\n";

			if (!($raw_contents = file_get_contents($this->current_url)))
			{
				echo "can't get |".$this->current_url."|\n";
				continue;
			}
			preg_match_all("/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(?:.*)<\/a>/siU", $raw_contents, $matches);
			$base = $this->getBaseUrl($raw_contents);
			foreach ($matches[2] as $url)
			{
				$url = $this->tidyUrl($url, $base);

				if (!in_array($url, $this->queue) &&
				    !isset($this->pages[$url]) &&
				    $url != $this->current_url &&
				    starts_with($url, $this->root_url) &&
				    !preg_match("/\.(jpg|gif|pdf|png)/i", $url))
				{
					$this->queue[] = $url;
				}
			}
			$form_parser = new HtmlFormParser($raw_contents);
			$newForm = false;
			foreach ($form_parser->parseForms() as $form)
			{
				$action = $this->tidyUrl($form["form_data"]["action"], $base);
				if (!in_array($action, $this->form_actions))
				{
					$newForm = true;
					$this->form_actions[] = $action;
				}
			}

			$query_string = preg_match("/\?/", $this->current_url);

			$risk = self::LOW_RISK;
			if ($query_string || $newForm)
			{
				if ($query_string && $newForm)
				{
					$risk = self::HIGH_RISK;
				}
				else
				{
					$risk = self::MEDIUM_RISK;
				}
			}

			$this->pages[$this->current_url] = $risk;
		}
	}

	private function tidyUrl($url, $base = null)
	{
		if (starts_with($url, "./"))
		{
			$url = substr($url, 2);
		}

		$url = url_to_absolute(!empty($base) ? $base : $this->root_url, $url);

		if (preg_match("/(.*)#/", $url, $matches))
		{
			$url = $matches[1];
		}

		return $url;
	}

	private function getBaseUrl($raw_contents)
	{
		preg_match_all("/<base href=\"([^\"]*)\" \/>/is", $raw_contents, $base_matches);
		if (isset($base_matches) && isset($base_matches[1][0]))
		{
			return $base_matches[1][0];
		}
	}

}